using UnityEngine;
using System.Collections;

[System.Serializable]
public class DespawnAfterTime : MonoBehaviour {
	
	public float deltaTime = 1.0f;
	public string triggerTag = "Player";
	public bool isTrigger = true;
	public GameObject objectToDespawn = null;
	public UnityEngine.SkinnedMeshRenderer skinnedObjectToDespawn = null;
	public bool debug = false;
	
	private bool started = false;
	private bool finished = false;
	private float startTime = 0f;
	
	// Current time is always higher than startTime
	// Subtract startTime with currentTime
	// Make a sub routine to check if that value is equal to seconds or more
	// startTime = 1f;
	// currentTime = 2f;
	// seconds = 1f;
	// float diff = currentTime-startTime;
	// diff is 1, 1 second has passed
	private float currentTime = 0f;
	private float diff;
	
	private bool debugCheckedTheDiff = false;
	private bool debugCalculatedDiff = false;
	
	// Use this for initialization
	void Start () {
		if (!isTrigger && !finished) {
			setTime();	
		}
	}
	
	void setTime() {
		currentTime = Time.deltaTime;	
		started = true;
	}
	
	// Update is called once per frame
	void Update () {
		if (started && !finished) {
			currentTime += Time.deltaTime;
			diff = currentTime-startTime;
			debugCalculatedDiff = true;
			if (diff >= deltaTime) {
				debugCheckedTheDiff = true;
				if (objectToDespawn != null) {
					objectToDespawn.renderer.enabled = false;
				}
				if (skinnedObjectToDespawn != null) {
					skinnedObjectToDespawn.renderer.enabled = false;
				}
				finished = true;
			}
		}
	}
	
	void OnTriggerEnter(Collider other) {
		if (other.tag == triggerTag && isTrigger && !finished) {
			setTime();
		}
	}
	
	void OnGUI() {
		if (debug) {
			GUI.Box(new Rect(0,0,200,400), 
				"Started? " + started + "\n" +
				"Finished: " + finished + "\n" +
				"Delta Time: " + deltaTime + "\n" +
				"Gone for: " + (diff) + "\n" +
				"Supposed to be finished? " + ((diff) >= deltaTime) + "\n" +
				"Calculated diff? " + debugCalculatedDiff + "\n" +
				"Checked diff? " + debugCheckedTheDiff);	
		}
	}
}
